package sailing.ui.systemsetting;

import java.awt.Window;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.jdesktop.application.SingleFrameApplication;

import sailing.entity.BankAccount;
import sailing.entity.BankName;
import sailing.listener.UI;
import sailing.managers.BankAccountManager;
import sailing.managers.BankNameManager;
import sailing.ui.base.CommonJDialog;
import sailing.ui.base.DateChooser;
import cjlite.logger.Logger;
import cjlite.utils.RandomUtils;
import cjlite.utils.TypeConverter;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

public class NewBankAccountDialog extends CommonJDialog {

	private static Logger logger = Logger.thisClass();

	private JComboBox<String> bankNameComb;

	private JTextField accountNameTF, accountNumTF, balanceTF, openTimeTF;

	private static String[] btnCaptions = { "确定", "取消" };

	private TypeConverter tc = new TypeConverter();

	DateChooser dateChooser;


	public NewBankAccountDialog(Window window, SingleFrameApplication singleFrameApplication) {
		super(window, "添加银行账户", ModalityType.APPLICATION_MODAL, singleFrameApplication);
	}


	@Override
	protected JPanel initialContentPanel() {
		JPanel root = new JPanel();
		root.setBorder(BorderFactory.createEmptyBorder(20, 20, 40, 20));
		
		FormLayout layout = new FormLayout("right:pref,4dlu,f:100dlu",
				"22dlu,2dlu,22dlu,2dlu,22dlu,2dlu,22dlu,2dlu,22dlu");

		root.setLayout(layout);	

		CellConstraints cc = new CellConstraints();
		// row 1
		root.add(new JLabel("开户银行名称："), cc.xy(1, 1));
		bankNameComb = new JComboBox<String>();
		root.add(bankNameComb, cc.xy(3, 1));
		// row 3
		root.add(new JLabel("银行账号户名："), cc.xy(1, 3));
		accountNameTF = new JTextField();
		root.add(accountNameTF, cc.xy(3, 3));
		// row 5
		root.add(new JLabel("银行账号："), cc.xy(1, 5));
		accountNumTF = new JTextField();
		root.add(accountNumTF, cc.xy(3, 5));
		// row 7
		root.add(new JLabel("初始余额："), cc.xy(1, 7));
		balanceTF = new JTextField();
		root.add(balanceTF, cc.xy(3, 7));
		// row 9
		root.add(new JLabel("开户时间："), cc.xy(1, 9));
		openTimeTF = new JTextField();
		dateChooser = DateChooser.getInstance("yyyy-MM-dd");
		dateChooser.register(openTimeTF);
		root.add(openTimeTF, cc.xy(3, 9));

		this.setSize(420, 400);
		this.updateData();
		return root;
	}


	private void updateData() {
		BankNameManager bnm = this.getApplication().getContext().getIoc().getInstance(BankNameManager.class);

		bankNameComb.addItem("请选择银行名称");
		for (BankName bn : bnm.getAllBankNameList()) {
			bankNameComb.addItem(bn.getName());
		}
	}


	@Override
	protected String[] getBottomBtnTxt() {
		return btnCaptions;
	}


	@Override
	protected void performBtnClick(String btnCaption) {
		if (btnCaption.equalsIgnoreCase(btnCaptions[0])) {
			this.performOKAction();
		} else {
			this.performCancelAction();
		}
	}


	protected void performCancelAction() {
		this.setVisible(false);
	}


	private void performOKAction() {
		BankAccount ba = new BankAccount();
		String msg = this.validateInput(ba);
		if (msg != null && msg.trim().length() > 0) {
			JOptionPane.showMessageDialog(this, msg, "错误！", JOptionPane.ERROR_MESSAGE);
			return;
		}

		ba.setId(RandomUtils.randomString16());
		ba.setCreateTime(System.currentTimeMillis());

		BankAccountManager bam = this.getApplication().getContext().getIoc().getInstance(BankAccountManager.class);
		if (bam.save(ba)) {
			JOptionPane.showMessageDialog(this, "添加成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
			this.setVisible(false);
			UI.refresh();
		} else {
			JOptionPane.showMessageDialog(this, "添加失败！", "错误！", JOptionPane.ERROR_MESSAGE);
		}
	}


	private String validateInput(BankAccount ba) {
		StringBuilder sb = new StringBuilder();
		String bn = (String) bankNameComb.getSelectedItem();
		if (bn == null || bn.equals("请选择银行名称")) {
			sb.append("+ 请选择银行名称\n");
		} else {
			ba.setBankName(bn);
		}

		String ban = this.accountNameTF.getText();

		if (ban == null || bn.trim().length() == 0) {
			sb.append("+ 请输入银行账户户名\n");
		} else {
			ba.setAccountName(ban);
		}

		String baNum = this.accountNumTF.getText();

		if (baNum == null || baNum.trim().length() == 0) {
			sb.append("+ 请输入银行账户的账号\n");
		} else {
			ba.setAccountNumber(baNum);
		}

		String ib = this.balanceTF.getText();

		if (ib == null || ib.trim().length() == 0) {
			sb.append("+ 请输入银行账户的初始余额\n");
		} else {
			try {
				double value = tc.convert(Double.class, ib);
				ba.setInitialBalance(value);
			} catch (Exception e) {
				logger.error("Error on converting String[{0}] to double", e, ib);
				sb.append("+ 请输入正确的银行账户初始余额\n");
			}
		}

		Date openDate = this.dateChooser.getDate();

		if (ib == null || ib.trim().length() == 0) {
			sb.append("+ 请输入银行账户的开户时间\n");
		} else {
			ba.setOpenTime(openDate.getTime());
		}

		return sb.toString();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see java.awt.Dialog#isResizable()
	 */
	@Override
	public boolean isResizable() {
		return false;
	}

}
